/* eslint-disable jsx-a11y/accessible-emoji */
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { SafeAreaView, ScrollView, StyleSheet } from 'react-native';
import { CreateTodo } from './CreateTodo';
import { TodoItem } from './Todo';
import { Task, TaskEntity } from './api';
import { DataSource } from 'typeorm/browser';



export const App = () => {
  const scrollViewRef = useRef<null | ScrollView>(null);

  const [todo,setTodo]=useState<Task[]>([] );

  const [connection, setConnection] = useState<DataSource | null>(null);

  useEffect( () => {
    setupConnection();
  }, []);

  useEffect(() => {
    connection&&getTasks()
  }, [connection]);

  const setupConnection = useCallback(async () => {
    try {
      const connection=   new DataSource({
        type: 'react-native',
        database: 'test',
        location: 'default',
        logging: ['error', 'query', 'schema'],
        synchronize: true,
        entities: [TaskEntity],
      })
     const dataSource= await connection.initialize()
      setConnection(dataSource);

    } catch (error) {
      console.log(error);
    }
  }, []);

  const getTasks = useCallback(async () => {

    const authorRepository = connection!.getRepository(TaskEntity);
    const result = await authorRepository.find();
    setTodo(result||[]);
  }, [connection]);





 async function  addTodoHandle(text:string){
    const newData = { title: text, done: false, order: 0, createTime: Date.now() };
    const authorRepository = connection!.getRepository(TaskEntity)

   const db = await authorRepository.save(newData);
   setTodo([ db,...todo,].map((item,index)=>({...item,order:index})));
  }

  async function doneHandle(task:Task){
    await connection!.getRepository(TaskEntity).update(task.id, { done: !task.done });
 const list= todo.map(item=>{
  if (item.id===task.id){
    return {...item,done:!item.done}
  }
  return { ...item };
})
    setTodo(list);
  }

  async function deleteHandle(task:Task){
    await connection!.getRepository(TaskEntity).delete(task.id);
    const list= todo.filter(item=>{
     return item.id!==task.id
    })
    setTodo(list);
  }

  return (
    <>
      <SafeAreaView style={[styles.section,{display:'flex',height:'100%'}]}>
       <CreateTodo style={{marginTop:12}} onAddTodo={addTodoHandle}/>
        <ScrollView
          ref={(ref) => {
            scrollViewRef.current = ref;
          }}
          contentInsetAdjustmentBehavior="automatic"
          style={[styles.scrollView,{flex:1}]}
        >

          {todo.map((value,index)=>{
            return (<TodoItem deleteHandle={deleteHandle} doneHandle={doneHandle} key={index} item={value}/>)
          })}

        </ScrollView>
      </SafeAreaView>

    </>
  );
};
const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: '#ffffff',
  },
  codeBlock: {
    backgroundColor: 'rgba(55, 65, 81, 1)',
    marginVertical: 12,
    padding: 12,
    borderRadius: 4,
  },
  monospace: {
    color: '#ffffff',
    fontFamily: 'Courier New',
    marginVertical: 4,
  },
  comment: {
    color: '#cccccc',
  },
  marginBottomSm: {
    marginBottom: 6,
  },
  marginBottomMd: {
    marginBottom: 18,
  },
  marginBottomLg: {
    marginBottom: 24,
  },
  textLight: {
    fontWeight: '300',
  },
  textBold: {
    fontWeight: '500',
  },
  textCenter: {
    textAlign: 'center',
  },
  text2XS: {
    fontSize: 12,
  },
  textXS: {
    fontSize: 14,
  },
  textSm: {
    fontSize: 16,
  },
  textMd: {
    fontSize: 18,
  },
  textLg: {
    fontSize: 24,
  },
  textXL: {
    fontSize: 48,
  },
  textContainer: {
    marginVertical: 12,
  },
  textSubtle: {
    color: '#6b7280',
  },
  section: {
    marginVertical: 24,
    marginHorizontal: 12,
  },
  shadowBox: {
    backgroundColor: 'white',
    borderRadius: 24,
    shadowColor: 'black',
    shadowOpacity: 0.15,
    shadowOffset: {
      width: 1,
      height: 4,
    },
    shadowRadius: 12,
    padding: 24,
    marginBottom: 24,
  },
  listItem: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
  },
  listItemTextContainer: {
    marginLeft: 12,
    flex: 1,
  },
  appTitleText: {
    paddingTop: 12,
    fontWeight: '500',
  },
  hero: {
    borderRadius: 12,
    backgroundColor: '#143055',
    padding: 36,
    marginBottom: 24,
  },
  heroTitle: {
    flex: 1,
    flexDirection: 'row',
  },
  heroTitleText: {
    color: '#ffffff',
    marginLeft: 12,
  },
  heroText: {
    color: '#ffffff',
    marginVertical: 12,
  },
  whatsNextButton: {
    backgroundColor: '#ffffff',
    paddingVertical: 16,
    borderRadius: 8,
    width: '50%',
    marginTop: 24,
  },
  learning: {
    marginVertical: 12,
  },
  love: {
    marginTop: 12,
    justifyContent: 'center',
  },
});

export default App;
